package com.ychen.ruijee.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ychen.ruijee.bean.Employee;
import com.ychen.ruijee.common.R;
import com.ychen.ruijee.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author ychen@gotop.cn
 * @date 2024-05-28 0:03
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Resource
    private EmployeeService employeeService;

    /**
     *  用户登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        R<Employee> result = employeeService.login(request,employee);
        return result;
    }

    /**
     * 用户退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        // 直接清理 session 中保存的 当前登录员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功！");
    }

    /**
     * 员工新增
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> saveEmployee(HttpServletRequest request,@RequestBody Employee employee){
        boolean flag = employeeService.saveEmployee(request,employee);
        return flag ? R.success("新增成功") : R.error("新增失败");


    }

    /**
     * 分页查询 展示
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> selectPage(@RequestParam(defaultValue = "1")  Integer page,
                                        @RequestParam(defaultValue = "10") Integer pageSize,
                                        String name){
        R<Page<Employee>> result = employeeService.selectPage(page,pageSize,name);
        return result;
    }

    /**
     * admin 禁用员工
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee){
        // 测试  发起修改操作 是不是 同一个线程完成的
        long id = Thread.currentThread().getId();
        log.error("测试  线程ID {}",id);

        boolean updateFlag = employeeService.updateStattus(request,employee);
        return updateFlag ? R.success("修改成功") : R.error("修改失败");
    }

    /**
     * 根据 id 查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        log.info("正在根据 id 查询....");
        Employee employee = employeeService.getById(id);
        if (employee != null){
            return R.success(employee);
        }
        return R.error("查询失败");

    }
}
